﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.BomCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理修改BOM命令
    /// </summary>
    public class BOMEditCommandHandelr : IRequestHandler<EditBomCommand, APIResult<object>>
    {
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBaseRepository<Bom> bomRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<OperationRecord> operaRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="bomRepository">仓储</param>
        public BOMEditCommandHandelr(IBaseRepository<Bom> bomRepository,IMapper mapper,IBaseRepository<OperationRecord> operaRepository)
        {
            this.bomRepository = bomRepository;
            this.mapper = mapper;
            this.operaRepository = operaRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">重置</param>
        /// <returns></returns>
        public async Task<APIResult<object>> Handle(EditBomCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var entity=mapper.Map<Bom>(request);
            entity.BomNode=request.BomNode;
            var i=bomRepository.UpdateAsync(entity).Result;
            OperationRecord operationRecord = new OperationRecord()
            {
                BomId = request.BomId,
                OperationName = "admin",
                OperationDate = DateTime.Now,
                OperationInfo = "修改"
            };
            await operaRepository.AddAsync(operationRecord);
            if (i > 0)
            {
                result.Code = APIEnums.修改成功;
                result.Msg = APIEnums.修改成功.ToString();
                result.data = i;
            }
            else
            {
                result.Code = APIEnums.修改失败;
                result.Msg = APIEnums.修改失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
